package com.zhoug.widget.dialog.menu;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.google.android.material.tabs.TabLayout;
import com.zhoug.common.adapters.recycler.BaseRecyclerViewAdapter;
import com.zhoug.common.adapters.recycler.BaseViewHolder;
import com.zhoug.widget.R;

import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.StyleRes;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.OrientationHelper;
import androidx.recyclerview.widget.RecyclerView;

/**
 * 多级菜单
 */
public class MenuDialog extends Dialog implements TabLayout.OnTabSelectedListener {
    private TabLayout mTabLayout;
    private RecyclerView mRecyclerView;
    private List<? extends Menu> menus;
    private MenuAdapter mAdapter;
    private Callback mCallback;
    private int selectColor=Color.parseColor("#22adff");

    public MenuDialog(@NonNull Context context) {
        super(context, R.style.widgets_dialog_full);
    }

    public MenuDialog(@NonNull Context context, List<? extends Menu> menus) {
        super(context,R.style.widgets_dialog_full);
        this.menus=menus;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//必须设置无标题 否则不会匹配内容
        setContentView(R.layout.widgets_dialog_menu_view);
        setWindowAnimations(R.style.widgets_anim_window_popu_down);
        setAttributes(width,height,gravity);
        setCanceledOnTouchOutside(true);
        init();

    }

    private void init(){
        mTabLayout=findViewById(R.id.tabLayout_menuView);
        mRecyclerView=findViewById(R.id.recyclerView_menuView);

        mAdapter = new MenuAdapter();
        mAdapter.setData(menus);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.addItemDecoration(new DividerItemDecoration(getContext(), OrientationHelper.VERTICAL));
        mRecyclerView.setAdapter(mAdapter);
        addTab(menus);
        mTabLayout.addOnTabSelectedListener(this);
    }

    private void addTab(List<? extends Menu> menus){
        if(menus==null)return;
        for(Menu menu1:menus){
            if(menu1!=null){
                menu1.setSelected(false);
            }
        }
        mTabLayout.addTab(mTabLayout.newTab().setText("请选择").setTag(menus));
    }

    /**
     * 移除指定位置后面的tab
     * @param position
     */
    private void removeTabLater(int position){
        int tabCount = mTabLayout.getTabCount();
        Log.d(TAG, "removeTabLater: position="+position);
        Log.d(TAG, "removeTabLater: tabCount="+tabCount);
       for(int i=tabCount-1;i>position;i--){
           mTabLayout.removeTabAt(i);
       }

    }

    /**
     * 选中指定位置的tab
     * @param position
     */
    private void select(int position){
        TabLayout.Tab tabAt = mTabLayout.getTabAt(position);
        if(tabAt!=null){
            tabAt.select();
        }
    }



    private class MenuAdapter<T extends Menu> extends BaseRecyclerViewAdapter<T> implements View.OnClickListener {

        @Override
        public int getLayoutId(int viewType) {
            return R.layout.widgets_dialog_menu_view_item;
        }


        @Override
        public void onBindData(BaseViewHolder holder, T data, int position, int viewType) {
            if(data!=null){
                TextView textView=holder.getView(R.id.menu_view_item);
                textView.setText( data.getName());
                holder.itemView.setTag(data);
                if(data.isSelected()){
                    textView.setTextColor(selectColor);
                }else{
                    textView.setTextColor(Color.BLACK);
                }
                holder.itemView.setOnClickListener(MenuAdapter.this);
            }
        }

        @Override
        public void onClick(View v) {
            Menu menu= (Menu) v.getTag();
            //清空选中状态
            List<Menu> data = mAdapter.getData();
            for(Menu menu1:data){
                menu1.setSelected(false);
            }
            //设为选中
            menu.setSelected(true);
            //选中后改变颜色


            //当前选择的tab名字修改为选择的菜单name
            int selectedTabPosition = mTabLayout.getSelectedTabPosition();
            TabLayout.Tab tabAt = mTabLayout.getTabAt(selectedTabPosition);
            if(tabAt!=null){
                tabAt.setText(menu.getName());
            }
            //如果后面的子菜单tab显示了,先移除后面的
            removeTabLater(selectedTabPosition);
            List<? extends Menu> child = menu.getChild();
            if(child ==null || child.size()==0){
//                Toast.makeText(getContext(),menu.getName() , Toast.LENGTH_SHORT).show();
                dismiss();
                if(mCallback!=null){
                    mCallback.onSelected(menu);
                }
            }else{
                //有子菜单,显示子菜单
                addTab(child);
                select(selectedTabPosition+1);
                mAdapter.setData(child);
            }

            mAdapter.notifyDataSetChanged();

        }
    }

    private static final String TAG = "MenuDialog";
    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        Log.d(TAG, "onTabSelected: tab="+tab.getText());
        List<Menu> list = (List<Menu>) tab.getTag();
        if(list==null)return;
        mAdapter.setData(list);
        mAdapter.notifyDataSetChanged();
        boolean hasSelect=false;
        for(int i = 0;i<list.size();i++){
            Menu menu = list.get(i);
            if(menu.isSelected()){
                hasSelect=true;
                scrollTo(i);
                break;
            }
        }
        if(!hasSelect){
            scrollTo(0);
        }
    }

    private void scrollTo(int position){
        mRecyclerView.scrollToPosition(position);
        try {
            LinearLayoutManager mLayoutManager =
                    (LinearLayoutManager) mRecyclerView.getLayoutManager();
            mLayoutManager.scrollToPositionWithOffset(position, 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {
        Log.d(TAG, "onTabUnselected: tab="+tab.getText());
    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {
        Log.d(TAG, "onTabReselected: tab="+tab.getText());
    }

    private int width=WindowManager.LayoutParams.MATCH_PARENT;
    private int height=WindowManager.LayoutParams.WRAP_CONTENT;
    private int gravity=Gravity.CENTER;

    /**
     *设置窗口的属性
     * @param width 窗口宽 例：WindowManager.LayoutParams.MATCH_PARENT
     * @param height 高 例：200
     * @param gravity 位子 例：Gravity.BOTTOM
     */
    public void setAttributes(int width,int height,int gravity){
        this.width=width;
        this.height=height;
        this.gravity=gravity;
        if(this.getWindow()!=null){
            WindowManager.LayoutParams attributes = this.getWindow().getAttributes();
            attributes.width=width;
            attributes.height= height;
            attributes.gravity= gravity;
            this.getWindow().setAttributes(attributes);
        }


    }

    /**
     * 设置动画
     * @param resId  R.style.anim_window_popu动 画
     */
    public void setWindowAnimations(@StyleRes int resId){
        if(getWindow()!=null){
            getWindow().setWindowAnimations(resId);
        }
    }



    public List<? extends Menu> getMenus() {
        return menus;
    }

    public void  setMenus(List<? extends Menu> menus) {
        this.menus = menus;
    }

    public void updateMenu(List<? extends Menu> menus){
        this.menus = menus;
        if(mTabLayout!=null){
            mTabLayout.removeAllTabs();
            addTab( this.menus);
        }
        if(mAdapter!=null){
            mAdapter.setData( this.menus);
            mAdapter.notifyDataSetChanged();
        }
    }

    public void notifyDataSetChanged(){
        if(mAdapter!=null){
            mAdapter.notifyDataSetChanged();
        }
    }

    public Callback getCallback() {
        return mCallback;
    }

    public void setCallback(Callback callback) {
        this.mCallback = callback;
    }

    public  interface Callback{
        void onSelected(Menu menu);

    }
}
